package fr.grassaud.hmvc.session;

import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fr.grassaud.hmvc.info.TriadInfo;
import fr.grassaud.hmvc.util.HMVCIntrospector;

/**
 * Simple listener to inject the HMVCSession in components of a <code>Triad</code>
 * @author vgrassaud
 *
 */
public class SessionTriadListener implements TriadListener {

    
    private HMVCSession session;
    
    private Logger logger = LoggerFactory.getLogger(SessionTriadListener.class);
    
    public  SessionTriadListener(HMVCSession session) {
	this.session = session;
    }
    
    @Override
    /**
     * Inject the spring beans when the triad is created.
     */
    public void onTriadCreated(Triad triad) {
	if (session != null) {
	    TriadInfo info = triad.getTriadInfo();
	    injectSpringBrean(triad.getController(), info.getControllerClass());
	    if (info.getModelClass() != null && triad.getModel() != null ) {
		injectSpringBrean(triad.getModel(), info.getModelClass());
	    }
	    injectSpringBrean(triad.getView(), info.getViewClass());
	}

    }

    private void injectSpringBrean(Object component, Class<?> componentClass) {
	for (Field f : HMVCIntrospector.getAllFields(componentClass)) {
	    if (f.isAnnotationPresent(SessionContext.class)) {
		f.setAccessible(true);
		try {
		    f.set(component, session);
		} catch (IllegalArgumentException e) {
		    logger.error("ERROR", e);
		} catch (IllegalAccessException e) {
		    logger.error("ERROR", e);
		}
	    }
	}
    }

    @Override
    /**
     * Does nothing 
     */
    public void onTriadInstanciated(Triad triad) {
	// do nothing
    }
}
